'use strict';

let fs=require('fs');
let path=require('path');
let router=require('koa-router')();

function getEach(dir) {
    let files=fs.readdirSync(dir);
    let controllerFiles=files.filter((name)=>{
        return name.endsWith('.js') && name !== 'index.js';
    })
    return controllerFiles;
}

function register(files) {
    files.forEach((item) => {
        let tmpPath=path.join(__dirname,item);
        let route=require(tmpPath);
        for(let key in route){
            let type=route[key][0];
            let fn=route[key][1];
            if (type === 'get'){
                router.get(key,fn);
            }else if(type === 'post'){
                router.post(key,fn);
            }else if(type === 'delete'){
                router.delete(key,fn);
            }else if(type === 'put'){
                router.put(key,fn);
            }
        }
    });
}

module.exports=function(currentDir){
    let dir =currentDir || __dirname;
    let controllerFiles=getEach(dir);
    register(controllerFiles);
    return router.routes();
}